package com.only.webServer.servlet;


import com.only.webServer.DispatcherServlet;
import com.only.webServer.request.HttpRequest;
import com.only.webServer.response.HttpResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class PublicServlet extends Servlet{

    private static String publicPath = "./Webpacks";

    private static Map<String, String> imgContentType = new HashMap<>();

    static {
        File file = new File(publicPath);
        if (!file.exists()) {
            boolean mkdir = file.mkdir();
            if (mkdir) {
                log.info("公共目录创建成功！");
            } else {
                log.error("公共目录创建失败");
            }
        }
        imgContentType.put("html", "text/html;charset=UTF-8");
        imgContentType.put("png", "image/png");
        imgContentType.put("jpg", "image/jpeg");
        imgContentType.put("ico", "image/x-icon");
        imgContentType.put("xml", "text/xml");
        imgContentType.put("css", "text/css");
        imgContentType.put("js", "application/x-javascript");
    }

    @Override
    public void doGet(HttpRequest request, HttpResponse response) {
        String mapping = request.getPathMapping();
        String path = null;
        // 是首页就访问 index.html
        if ("/".equals(mapping)) {
            path = "/index.html";
        } else {
            path = mapping;
        }
        // 判断文件是否存在
        File file = new File(publicPath + path);
        if (!file.exists()) {
            request.setPathMapping("/404");
            DispatcherServlet.dispense(request, response);
            return;
        }
        // 文件存在判断类型 只支持返回 html、png、jpg 其他类型以流返回
        String fileSuffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        try {
            // 将文件流中的数据读取到字节数组中
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));
            byte[] fileBuff = new byte[stream.available()];
            stream.read(fileBuff);
            stream.close();
            // 响应
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Length", String.valueOf(fileBuff.length));
            //如果不是支持类型直接返回二进制流
            response.setHeader("Content-Type", imgContentType.getOrDefault(fileSuffix, "application/octet-stream"));
            response.setBody(fileBuff);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void doPost(HttpRequest request, HttpResponse response) {
        doGet(request, response);
    }
}
